import { uuid, getIn } from './util';


var subMap = {};
export default function Connect(path, component, bindState) {
	if (!component instanceof Laya.Node) console.warn("component unusable");
	let pathName = path/*.replace(/\./g, "_")*/;
	if (!component.uuid) { 
		component.uuid = uuid();
		component.state = {};
		component.preState = {};
		component.bindState = {};
	}
	if (!subMap[pathName]) {  subMap[pathName] = {}; }

	subMap[pathName][component.uuid] = component;

	let _state = getIn(Connect.store, path);
	if (typeof bindState === "function") {
		component.bindState[pathName] = bindState;
		bindState(_state); 
	}
	component.state[pathName] = _state;
}

Connect.provider = function(store) {
	if (Connect.store) { console.warn("store be used"); }
	Connect.store = store;
	Connect.unsubscribe = store.subscribe(() => {
		Object.keys(subMap).forEach( path => {
			let pathName = path/*.replace(/\./g, "_")*/;
			Object.keys(subMap[pathName]).forEach( uuid => {
				let component = subMap[pathName][uuid];
				let _state = getIn(Connect.store, path);
				if (!component||component.destroyed) return delete subMap[pathName][uuid];
				if (component.state[pathName] !== _state) {
					if (typeof component.bindState[pathName] === "function") {
						let bindState = component.bindState[pathName];
						bindState.call(component, _state, component.state[pathName]);
					}
					component.preState[pathName] = component.state[pathName];
					component.state[pathName] = _state;
				}
			});
		});
	});
};
